package com.example.jpa.crud.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

@Service
public class JsonServiceForSpringBoot3 implements JsonService {

    private static final Logger log = LoggerFactory.getLogger(JsonServiceForSpringBoot3.class);

    private ObjectMapper objectMapper;

    @PostConstruct
    public void init() {
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public Optional<Map<String, Object>> fromBytes(byte[] bytes) {
        try {
            return Optional.ofNullable(objectMapper.readValue(bytes, new TypeReference<Map<String, Object>>() {
            }));
        } catch (IOException exception) {
            log.error("fromBytes", exception);
            return Optional.empty();
        }
    }

    @Override
    public String toJson(Object object) {
        if (object == null) {
            return "null";
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("toJson", e);
        }
        return "null";
    }


}
